import { Message, MessageBox } from 'element-ui'
import _ from 'lodash'

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

export function getUrlParams(url) {
  return Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {
    const [f, v] = m.split('=')
    return {
      [f]: v
    }
  }))
}

export function getJsonTree(data, id = 'id', parentId = 'parent') {
  data.forEach(function(item) {
    delete item.children
  })
  const map = {}
  data.forEach(function(item) {
    map[item[id]] = item
  })

  const val = []
  data.forEach(function(item) {
    const parent = map[item[parentId]]

    if (parent) {
      (parent.children || (parent.children = [])).push(item)
    } else {
      val.push(item)
    }
  })

  return val
}

export function typeOf(res) {
  return Object.prototype.toString.call(res).match(/^\[.* (.*)\]$/)[1].toLowerCase()
}

export function msg(msg = '提示', type = 'info') {
  Message({
    message: msg,
    type: type
  })
}

export function prompt(txt = '确认进行此操作?', type = 'info') {
  return new Promise((resolve) => {
    MessageBox.confirm(txt, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: type,
      dangerouslyUseHTMLString: true
    })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        return false
      })
  })
}

export function findArrKey(arr) {
  const parent = []
  const allnode = []
  arr.forEach(item => {
    parent.push(item.parent)
    allnode.push(item.id)
  })
  return _.difference(allnode, parent)
}

/* ---------------- 过滤条件 --------------------*/
export const noEmpty = el => el

/* ---------------- 工具方法 --------------------*/

/*
* @method 根据条件过滤Map
* @param {function} f 过滤条件
* @params {json} map 数据
* */
export const filterJson = _.curry((f, json) => {
  const res = {}
  for (const key in json) {
    const val = json[key]
    if (f(val)) {
      res[key] = val
    }
  }
  return res
})

export const filterEmptyJson = filterJson(noEmpty)

/*
* @method 表格数据导出excel
* @param {object} option 参数配置
*   @params {array} tHeader 表头文字 默认 []
*   @params {array} filterVal 对应字段名 默认 []
*   @params {array} table 表格数据 默认 []
*   @params {string} fileName 导出excel文件名 默认 excel-file
* @param {function} 导出成功回调
* */

const formatJson = (filterVal, jsonData) => {
  return jsonData.map(v => filterVal.map(j => v[j]))
}

export const exportFile = (option = {}, cb) => {
  import('@/vendor/Export2Excel').then(excel => {
    const tHeader = option.tHeader || [] // 对应表格输出的title
    const filterVal = option.filterVal || []
    const table = option.table || []
    const data = formatJson(filterVal, table)
    excel.export_json_to_excel({
      header: tHeader,
      data,
      filename: option.fileName || 'excel-file'
    })
    cb && cb()
  })
}

/*
* 树状数据递归
* **/

export const getTrees = (list, parentId) => {
  const items = {}
  // 获取每个节点的直属子节点，*记住是直属，不是所有子节点
  for (let i = 0; i < list.length; i++) {
    const key = list[i].parentCode
    if (items[key]) {
      items[key].push(list[i])
    } else {
      items[key] = []
      items[key].push(list[i])
    }
  }
  return formatTree(items, parentId)
}

export const formatTree = (items, parentId) => {
  const result = []
  if (!items[parentId]) {
    return result
  }
  for (const t of items[parentId]) {
    const child = formatTree(items, t.value)
    if (child.length > 0) {
      t.children = formatTree(items, t.value)
    }
    result.push(t)
  }
  return result
}

/*
* 打开新窗口执行事件
*
* */

export const openWin = (dom, cb) => {
  const win = window.open('')
  win.document.write(dom || '<h1>new Window</h1>')
  cb && cb(win)
}

/*
* 选取dom
* */
export const e = name => document.querySelector(name)
export const es = name => document.querySelectorAll(name)

/*
* 找出json中空字段
* */

export const findEmptyWithJson = (json, arr = []) => {
  const res = []
  if (arr.length === 0) {
    arr = Object.keys(json)
  }
  arr.forEach(el => {
    if (!json[el]) {
      res.push(el)
    }
  })
  return res
}

export const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

export const arrSum = (arr, key) => {
  let res = 0
  arr.forEach(item => {
    const val = key ? item[key] : item
    res += val
  })
  return res
}

// 过滤json数据中空数据
export const filterData = (json) => {
  for (const key in json) {
    if (json[key] === '') {
      delete json[key]
    }
  }
}
